import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../utils/g.dart';
import '../../utils/widgets/my_sliver_delegate.dart';
import 'list/my_list.dart';
import 'list/my_grid.dart';

class ProductList extends StatefulWidget {
  String sid;
  String cate_name;
  ProductList(
      {Key? key, required String this.sid, required String this.cate_name})
      : super(key: key);

  @override
  _ProductListState createState() => _ProductListState();
}

class _ProductListState extends State<ProductList> {
  List list = [];
  bool isList = false; // 标识商品列表的展示方式: 列表|网格
  int page = 1;
  List types = [
    {'key': 'catename', 'title': ''},
    {'key': 'priceOrder', 'title': '价格'},
    {'key': 'salesOrder', 'title': '销量'},
    {'key': 'news', 'title': '新品'},
  ];
  String type = 'catename';
  int currentIndex = 0;

  int _news = 0;
  String _priceOrder = "";
  String _salesOrder = "";
  Widget _priceOrderIcon = const Icon(Icons.expand_less, size: 20);
  Widget _salesOrderIcon = const Icon(Icons.expand_less, size: 20);

  // List<String> items = ["1", "2", "3", "4", "5", "6", "7", "8"];
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _onRefresh();
  }

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(const Duration(milliseconds: 1000));

    var res = await G.api.product.getListByCategory(
        sid: widget.sid,
        page: 1,
        news: _news,
        priceOrder: _priceOrder,
        salesOrder: _salesOrder);
    if (res['status'] == 200) {
      list = res['data'];
    }
    if (mounted) setState(() {});
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    page++;
    // monitor network fetch
    await Future.delayed(const Duration(milliseconds: 400));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    var res = await G.api.product.getListByCategory(
        sid: widget.sid,
        page: page,
        news: _news,
        priceOrder: _priceOrder,
        salesOrder: _salesOrder);
    if (res['status'] == 200) {
      list.addAll(res['data']);
    }

    if (mounted) {
      setState(() {});
    }

    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    var listIcon = Icon(isList ? Icons.view_list : Icons.view_module, size: 36);
    types[0]['title'] = widget.cate_name;

    return Scaffold(
        appBar: AppBar(
          title: const Text('商品列表'),
          centerTitle: true,
          actions: [
            InkWell(
                onTap: () {
                  setState(() {
                    isList = !isList;
                  });
                },
                child: listIcon),
            const SizedBox(
              width: 10,
            )
          ],
        ),
        // body: Text(widget.cate_name)
        body: _renderFreshList());
  }

  Widget _renderFreshList() {
    return SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: const WaterDropHeader(),
        footer: _renderCustomFooter(),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: CustomScrollView(
          slivers: [
            // 没有吸顶效果的导航菜单
            // SliverToBoxAdapter(
            //   child: Container(
            //     height: 50,
            //     color: Colors.grey.shade100,
            //     child: ListView.builder(
            //       itemCount: types.length,
            //       scrollDirection: Axis.horizontal,
            //       itemBuilder: (cxt, index) {
            //         return _renderType(index);
            //       }
            //     )
            //   )
            // ),

            // 具有吸顶效果的导航菜单
            SliverPersistentHeader(
                pinned: true, // 吸顶
                floating: true, // 反向滚动时，内容是否立即变大
                delegate: MySliverDelegate(
                    minHeight: 50,
                    maxHeight: 50,
                    child: Container(
                        height: 50,
                        child: ListView.builder(
                            itemCount: types.length,
                            scrollDirection: Axis.horizontal,
                            itemBuilder: (cxt, index) {
                              return _renderType(index);
                            })))),
            SliverPadding(
              padding: const EdgeInsets.all(10.0),
              sliver: _renderList(),
            )
          ],
        ));
  }

  Widget _renderType(int i) {
    return GestureDetector(
        child: Container(
            width: G.width / types.length,
            alignment: Alignment.center,
            padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 10),
            decoration: BoxDecoration(
                color: currentIndex == i
                    ? Colors.blue.shade100
                    : Colors.grey.shade100,
                border: Border(
                    bottom: BorderSide(
                  width: 3,
                  color: currentIndex == i
                      ? Colors.blue.shade200
                      : Colors.grey.shade100,
                ))),
            child: ['priceOrder', 'salesOrder'].contains(types[i]['key'])
                ? Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(types[i]['title'],
                          style: TextStyle(
                              color: currentIndex == i
                                  ? Theme.of(context).primaryColor
                                  : Colors.black45,
                              fontWeight: currentIndex == i
                                  ? FontWeight.w600
                                  : FontWeight.w400,
                              fontSize: 16)),
                      types[i]['key'] == 'priceOrder'
                          ? _priceOrderIcon
                          : _salesOrderIcon
                    ],
                  )
                : Text(types[i]['title'],
                    style: TextStyle(
                        color: currentIndex == i
                            ? Theme.of(context).primaryColor
                            : Colors.black45,
                        fontWeight: currentIndex == i
                            ? FontWeight.w600
                            : FontWeight.w400,
                        fontSize: 16))),
        onTap: () {
          currentIndex = i;
          type = types[i]['key'];
          if (type == 'priceOrder') {
            // 对排序方式的判断
            if (_priceOrder == "" || _priceOrder == "desc") {
              _priceOrder = "asc"; // 升序
              _priceOrderIcon = const Icon(Icons.expand_less, size: 20);
            } else {
              _priceOrder = "desc";
              _priceOrderIcon = const Icon(Icons.expand_more, size: 20);
            }
            _salesOrder = "";
            _news = 0;
          } else if (type == 'salesOrder') {
            // 对排序方式的判断
            if (_salesOrder == "" || _salesOrder == "desc") {
              _salesOrder = "asc"; // 升序
              _salesOrderIcon = const Icon(Icons.expand_less, size: 20);
            } else {
              _salesOrder = "desc";
              _salesOrderIcon = const Icon(Icons.expand_more, size: 20);
            }
            _priceOrder = "";
            _news = 0;
          } else if (type == 'news') {
            _news = 1;
            _salesOrder = "";
            _priceOrder = "";
          } else {
            _news = 0;
            _salesOrder = "";
            _priceOrder = "";
          }

          // 重新发送请求
          _onRefresh();
        });
  }

  Widget _renderCustomFooter() {
    return CustomFooter(
      builder: (BuildContext context, LoadStatus? mode) {
        Widget body;
        if (mode == LoadStatus.idle) {
          body = const Text("pull up load");
        } else if (mode == LoadStatus.loading) {
          body = const CupertinoActivityIndicator();
        } else if (mode == LoadStatus.failed) {
          body = const Text("Load Failed!Click retry!");
        } else if (mode == LoadStatus.canLoading) {
          body = const Text("release to load more");
        } else {
          body = const Text("No more Data");
        }
        return Container(
          height: 55.0,
          child: Center(child: body),
        );
      },
    );
  }

  // 渲染列表
  Widget _renderList() {
    if (isList) {
      return MyList(list: list);
    } else {
      return MyGrid(list: list);
    }
  }
}
